package com.thf.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.thf.pay.AlipayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class ProfuctInfoPayController {
    @RequestMapping("/product/info/pay")
    public void productToPay(Double price , Integer id , HttpServletResponse response){
        System.out.println("输出结果============》"+price+"===="+id);
        try {
            String body = aliPay(price, id);
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            try(PrintWriter out =response.getWriter()){
                out.println(body);
            }catch (IOException e) {
                e.printStackTrace();
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }
    private String aliPay(Double price , Integer id ) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(AlipayConfig.notify_url);
        request.setReturnUrl(AlipayConfig.return_url);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "208214985686219570852155314213"+id);
        bizContent.put("total_amount", price);
        bizContent.put("subject", "华瑞商品");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getBody());
            return response.getBody();
        } else {
            System.out.println("调用失败");
            return "";
        }
    }
}
